package com.credithc.customers.manager.service.impl;

import com.credithc.baseserv.core.utils.UUIDUtils;
import com.credithc.baseserv.pageHelper.PageInfo;
import com.credithc.customers.base.codes.CustomerCodes;
import com.credithc.customers.base.exception.CustomerException;
import com.credithc.customers.base.mapper.DictMapperMapper;
import com.credithc.customers.base.mapper.SystemDictMapper;
import com.credithc.customers.base.po.DictMapperPo;
import com.credithc.customers.base.po.SystemDictPo;
import com.credithc.customers.base.ro.DictMapperRo;
import com.credithc.customers.base.service.ICacheService;
import com.credithc.customers.base.vo.DictMapperVo;
import com.credithc.customers.manager.service.IDictMapperService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author zhukai
 * @date 2019/1/17 16:58
 */
@Service
@Slf4j
public class DictMapperServiceImpl implements IDictMapperService {

    private final DictMapperMapper dictMapperMapper;

    private final SystemDictMapper systemDictMapper;

    private static Map<String, Map<String, String>> dictMap;
    @Autowired
    private ICacheService cacheService;
    @Autowired
    public DictMapperServiceImpl(DictMapperMapper dictMapperMapper, SystemDictMapper systemDictMapper) {
        this.dictMapperMapper = dictMapperMapper;
        this.systemDictMapper = systemDictMapper;
    }

    @Override
    public PageInfo<DictMapperVo> getMapperList(Integer pageNo, Integer pageSize) {
        try {
            Page<DictMapperPo> page = PageHelper.startPage(pageNo, pageSize);
            List<DictMapperPo> poList = dictMapperMapper.selectAll();
            List<DictMapperVo> voList = new ArrayList<>();
            initDictMap();
            for (DictMapperPo po : poList) {
                DictMapperVo vo = new DictMapperVo();
                BeanUtils.copyProperties(po, vo);
                String mapperType = po.getMapperType();
                String dictCode = po.getDictCode();
                vo.setDictName(getSystemDictName(mapperType.split("_")[1], dictCode.split("_")[1]));
                vo.setMapperTypeName(getSystemDictName(mapperType.split("_")[0],mapperType.split("_")[1]));
                if (StringUtils.isNotEmpty(po.getSystemSign())) {
                    vo.setSystemSignName(cacheService.getSystemNameBySign(po.getSystemSign()));
                }
                voList.add(vo);
            }
            dictMap.clear();
            return new PageInfo(voList, (int) page.getTotal(), pageNo, pageSize);
        } catch (Exception e) {
            log.error("查询映射报错", e);
            throw new CustomerException(CustomerCodes.DATABASE_ERROR_QUERY);
        }
    }

    @Override
    public int insertDictMapper(DictMapperRo ro) {
        try{
            DictMapperPo po = new DictMapperPo();
            BeanUtils.copyProperties(ro,po);
            po.setId(UUIDUtils.getUUID());
            po.setCreateTime(new Timestamp(System.currentTimeMillis()));
            return dictMapperMapper.insert(po);
        }catch (Exception e){
            log.error("新增字典映射报错",e);
            throw new CustomerException(CustomerCodes.DATABASE_ERROR_INSERT);
        }
    }

    @Override
    public int updateDictMapper(String id, DictMapperRo ro) {
        try{
            DictMapperPo po = dictMapperMapper.selectByPrimaryKey(id);
            BeanUtils.copyProperties(ro,po);
            return dictMapperMapper.updateByPrimaryKey(po);
        }catch (Exception e){
            log.error("更新字典映射报错",e);
            throw new CustomerException(CustomerCodes.DATABASE_ERROR_UPDATE);
        }
    }

    @Override
    public int deleteDictMapper(String id) {
        try{
            return dictMapperMapper.deleteByPrimaryKey(id);
        }catch (Exception e){
            log.error("删除字典映射报错",e);
            throw new CustomerException(CustomerCodes.DATABASE_ERROR_DELETE);
        }
    }

    @Override
    public int deleteDictMappers(List<String> ids) {
        try{
            Example example = new Example(DictMapperPo.class);
            example.setDistinct(false);
            Example.Criteria criteria = example.createCriteria();
            criteria.andIn("id",ids);
            return dictMapperMapper.deleteByExample(example);
        }catch (Exception e){
            log.error("批量删除字典映射报错",e);
            throw new CustomerException(CustomerCodes.DATABASE_ERROR_DELETE);
        }
    }


    private void initDictMap() {
        dictMap = new HashMap<>();
        dictMap.clear();
        List<SystemDictPo> systemDictPos = systemDictMapper.selectAll();
        for (SystemDictPo po : systemDictPos) {
            String type = po.getType();
            String code = po.getCode();
            String name = po.getName();
            Map<String, String> valueMap;
            if (!dictMap.containsKey(type)) {
                valueMap = new HashMap<>();
            } else {
                valueMap = dictMap.get(type);
            }
            valueMap.put(code, name);
            dictMap.put(type, valueMap);
        }
    }

    private String getSystemDictName(String t, String c) {
        if (dictMap.containsKey(t)) {
            Map<String, String> map = dictMap.get(t);
            if (map.containsKey(c)) {
                return map.get(c);
            }
        }
        return null;
    }

}
